<template>
  <div class="user-management-container">
    <el-card class="management-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2 class="title">用户管理</h2>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户"
              style="width: 300px"
              clearable
              @keyup.enter="loadUsers"
            >
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table
        :data="userList"
        v-loading="loading"
        style="width: 100%"
        stripe
        row-key="userId"
      >
        <el-table-column label="用户信息" min-width="220">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="50" :src="row.avatar" class="user-avatar">
                <el-icon :size="30" v-if="!row.avatar">
                  <UserFilled />
                </el-icon>
              </el-avatar>
              <div class="user-detail">
                <h3 class="username">{{ row.username }}</h3>
                <p class="user-id">ID: {{ row.userId }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="mobile" label="手机号" width="150" />
        <el-table-column prop="email" label="邮箱" width="220" />

        <el-table-column label="角色" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.role === 1 ? '' : 'success'">
              {{ row.role === 1 ? "普通用户" : "管理员" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? "已启用" : "已禁用" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button
              size="small"
              :type="row.status === 1 ? 'danger' : 'success'"
              @click="toggleUserStatus(row)"
            >
              {{ row.status === 1 ? "禁用" : "启用" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadUsers"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, UserFilled } from "@element-plus/icons-vue";
import { UserControllerService } from "@/generated";

// 用户数据
const userList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchKeyword = ref("");

// 加载用户数据
const loadUsers = async () => {
  try {
    loading.value = true;
    const res = await UserControllerService.pageListUser({
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
    });
    console.log("用户数据加载成功", res);
    if (res.code === 0) {
      userList.value = res.data.records;
      total.value = parseInt(res.data.total);
    }
  } catch (error) {
    ElMessage.error("用户数据加载失败");
  } finally {
    loading.value = false;
  }
};

// 切换用户状态
const toggleUserStatus = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.status === 1 ? "禁用" : "启用"}用户 ${user.username} 吗？`,
      "操作确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const res = await UserControllerService.disableUser({
      userId: user.userId,
      status: user.status === 1 ? 0 : 1,
    });

    if (res.code === 0) {
      ElMessage.success("操作成功");
      loadUsers();
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("操作失败");
    }
  }
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  loadUsers();
};

// 初始化加载
onMounted(() => {
  loadUsers();
});
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.management-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.title {
  margin: 0;
  color: #1a1a1a;
  font-size: 24px;
  font-weight: 600;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 8px 0;

  .user-avatar {
    margin-right: 16px;
    flex-shrink: 0;
  }

  .user-detail {
    .username {
      margin: 0;
      font-size: 16px;
      color: #333;
    }

    .user-id {
      margin: 4px 0 0;
      color: #999;
      font-size: 12px;
    }
  }
}

.pagination-wrapper {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table__row) {
  transition: background-color 0.3s;

  &:hover {
    background-color: #f8f9fa;
  }
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .user-info {
    flex-direction: column;
    align-items: flex-start;

    .user-avatar {
      margin-bottom: 8px;
    }
  }
}
</style>
